package com.ebt.m.commons.buscomponent.thirtylogin;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.ebt.m.commons.buscomponent.thirtylogin.api.WechatApiService;
import com.ebt.m.commons.buscomponent.thirtylogin.model.PlatformActionListener;
import com.ebt.m.commons.buscomponent.thirtylogin.model.ShareListener;
import com.ebt.m.commons.buscomponent.thirtylogin.wechat.WechatLoginManager;
import com.ebt.m.commons.buscomponent.thirtylogin.wechat.WechatShareManager;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import org.json.JSONObject;

import java.util.HashMap;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by andy.wang on 2016/10/31.
 */

public class WechatHandlerActivity extends Activity implements IWXAPIEventHandler {
    private IWXAPI mIWXAPI;

    private PlatformActionListener mPlatformActionListener;
    private ShareListener mShareListener;

    private static final String API_URL = "https://api.weixin.qq.com";

    /**
     * BaseResp的getType函数获得的返回值，1:第三方授权， 2:分享
     */
    private static final int TYPE_LOGIN = 1;

    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = WechatHandlerActivity.this;
        mIWXAPI = WechatLoginManager.getIWXAPI();
        if (mIWXAPI == null){
            mIWXAPI = new WechatLoginManager(this).getIWXAPI();
        }
        if (mIWXAPI != null) {
            mIWXAPI.handleIntent(getIntent(), this);
        }
        finish();
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (mIWXAPI != null) {
            mIWXAPI.handleIntent(getIntent(), this);
        }
        finish();
    }

    @Override
    public void onReq(BaseReq baseReq) {
        finish();
    }

    @Override
    public void onResp(BaseResp resp) {
        mPlatformActionListener = WechatLoginManager
                .getPlatformActionListener();
        mShareListener = WechatShareManager.getShareListener();
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if (resp.getType() == TYPE_LOGIN) {
                    final String code = ((SendAuth.Resp) resp).code;

                    getApiService().getAccessToken(ShareBlock.getInstance().getWechatAppId(), ShareBlock.getInstance().getWechatSecret()
                            , code, "authorization_code")
                            .flatMap(responseBodyResponse -> {
                                             try {
                                                 JSONObject jsonObject = new JSONObject(responseBodyResponse.body().string());
                                                 final String accessToken = jsonObject
                                                         .getString("access_token");
                                                 final String openId = jsonObject.getString("openid");
                                                 return getApiService().getWechatUserInfo(accessToken, openId);
                                             } catch (Exception e) {
                                                 throw new RuntimeException();
                                             }
                                     }
                            )
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribeOn(Schedulers.io())
                            .subscribe(new Observer<Response<ResponseBody>>() {


                                @Override
                                public void onError(Throwable e) {
                                    if (mPlatformActionListener != null) {
                                        mPlatformActionListener.onError(ShareConstants.THIRTY_TYPE_WECHAT, "获取微信个人信息失败");
                                    }
                                }

                                @Override
                                public void onComplete() {

                                }

                                @Override
                                public void onSubscribe(Disposable d) {

                                }

                                @Override
                                public void onNext(Response<ResponseBody> response) {
                                    try {

                                        JSONObject jsonObject = new JSONObject(
                                                response.body().string());

                                        HashMap<String, Object> userInfoHashMap
                                                = new HashMap<String, Object>();
                                        userInfoHashMap
                                                .put(ShareConstants.PARAMS_NICK_NAME,
                                                        jsonObject.getString(
                                                                "nickname"));
                                        userInfoHashMap
                                                .put(ShareConstants.PARAMS_SEX,
                                                        jsonObject.getInt(
                                                                "sex"));
                                        userInfoHashMap
                                                .put(ShareConstants.PARAMS_IMAGEURL,
                                                        jsonObject.getString(
                                                                "headimgurl"));
                                        userInfoHashMap
                                                .put(ShareConstants.PARAMS_USERID,
                                                        jsonObject
                                                                .getString(
                                                                        "unionid"));
                                        if (mPlatformActionListener != null) {
                                            mPlatformActionListener
                                                    .onComplete(ShareConstants.THIRTY_TYPE_WECHAT, userInfoHashMap);
                                        }

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        onError(e);
                                    }
                                }
                            });
                } else {
                    if(mShareListener!=null){
                        mShareListener.onShareCompleteWrapper();
                    }
                }

                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:

                if (resp.getType() == TYPE_LOGIN) {
                    if (mPlatformActionListener != null) {
                        mPlatformActionListener
                                .onCancel(ShareConstants.THIRTY_TYPE_WECHAT);
                    }
                }else{
                    if(mShareListener!=null){
                        mShareListener.onShareCancelWrapper();
                    }
                }

                break;
            case BaseResp.ErrCode.ERR_SENT_FAILED:
                if (resp.getType() == TYPE_LOGIN) {
                    if (mPlatformActionListener != null) {
                        mPlatformActionListener
                                .onError(ShareConstants.THIRTY_TYPE_WECHAT, "微信授权失败");
                    }
                }else{
                    if(mShareListener!=null){
                        mShareListener.onShareErrorWrapper("微信分享失败");
                    }
                }
                break;
        }
        finish();
    }

    private WechatApiService getApiService() {
        Retrofit retrofit0 = new Retrofit.Builder()
                .baseUrl(API_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit0.create(WechatApiService.class);
    }
}
